{% extends 'admin/base.html' %}
{% load static %}

{% block title %}项目管理{% endblock %}
{% block css %}
<link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet">
<style>
    .modal-dialog {
        max-width: 1400px;
    }
    .text-ellipsis {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        max-width: 100%;
    }
    .text-ellipsis-multiline {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    #editor-wrapper {
        border: 1px solid #ccc;
        z-index: 100;
    }
    #toolbar-container {
        border-bottom: 1px solid #ccc;
    }
    #image_preview {
        max-width: 100px;
        max-height: 100px;
        cursor: pointer;
        background-color: #f0f0f0; /* 背景色作为占位符 */
        display: flex;
        align-items: center;
        justify-content: center;
    }
    #image_preview.enlarged {
        max-width: none;
        max-height: none;
        width: auto;
        height: auto;
    }
    #editor-container {
        height: 500px;
    }
</style>
{% endblock %}
{% block pagecontent %}
<h1 class="h3 mb-2 text-gray-800 mb-2">项目管理</h1>

<div class="card shadow mb-4">
    <div class="card-header" style="text-align: end">
        <button class="btn btn-dark btn-sm" id="add_project" data-toggle="modal" data-target="#AddModal">
            <a href="javascript:void(0);" style="color: #ffffff; text-decoration: none">添加项目</a>
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-sm table-striped" id="ProjectTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th style="width: 10%">项目名称</th>
                        <th style="width: 10%">项目经理</th>
                        <th style="width: 10%">中标金额(万元)</th>
                        <th style="width: 10%">工期(天)</th>
                        <th style="width: 20%">工程状态</th>
                        <th style="width: 30%" class="text-ellipsis">施工内容</th>
                        <th style="width: 10%">操作</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="AddModal" tabindex="-1" role="dialog" aria-labelledby="AddLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="AddLabel">添加项目</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="container-fluid">
                    <div class="input-group col-md-12 row mb-3">
                        <label for="project_name" class="col-sm-2 col-form-label">项目名称</label>
                        <input type="text" class="form-control col-sm-10" placeholder="项目名称" id="project_name" required>
                    </div>
                    <div class="input-group col-md-12 row mb-3">
                        <label for="project_manager" class="col-sm-2 col-form-label">项目经理</label>
                        <input type="text" class="form-control col-sm-10" placeholder="项目经理" id="project_manager" required>
                    </div>
                    <div class="input-group col-md-12 row mb-3">
                        <label for="bid_amount" class="col-sm-2 col-form-label">中标金额</label>
                        <input type="number" class="form-control col-sm-10" placeholder="中标金额（万元）" id="bid_amount" step="0.01" required>
                    </div>
                    <div class="input-group col-md-12 row mb-3">
                        <label for="duration" class="col-sm-2 col-form-label">工期</label>
                        <input type="number" class="form-control col-sm-10" placeholder="工期（天）" id="duration" required>
                    </div>
                    <div class="input-group col-md-12 row mb-3">
                        <label for="status" class="col-sm-2 col-form-label">工程状态</label>
                        <select class="form-control col-sm-10" id="status" required>
                            <option value="construction">施工中</option>
                            <option value="accepted">已验收</option>
                            <option value="not_accepted">未验收</option>
                            <option value="overdue_accepted">工期已过已验收</option>
                            <option value="abandoned">放弃中标</option>
                        </select>
                    </div>
                    <div class="input-group col-md-12 row mb-3">
                        <label for="project_content" class="col-sm-2 col-form-label">施工内容</label>
                        <textarea class="form-control col-sm-10" id="project_content" rows="5" placeholder="请输入施工内容"></textarea>
                    </div>

                    <div class="input-group col-md-12 row mb-3">
                        <label for="cover_image" class="col-sm-2 col-form-label">项目图片</label>
                        <input type="file" class="form-control-file col-sm-10" id="cover_image" accept="image/*" onchange="previewImage();">
                        <div class="col-sm-10 offset-sm-2 mt-2">
                            <img id="image_preview" src="" alt="项目图片预览" style="display: none;">
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary btn-sm" id="saveButton" onclick="submit_project()">保存</button>
                <button type="button" class="btn btn-primary btn-sm" id="updateButton" style="display: none;" onclick="update_project()">修改</button>
                <button type="button" class="btn btn-sm" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script>
// 全局变量
let isEditMode = false;
let currentProjectId = null;
let table;
let imageUploadUrl = null; // 用于保存图片上传的URL

// CSRF Token获取
function getCSRFToken() {
    let name = "csrftoken";
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 重置表单
function resetForm() {
    $('#project_name').val('');
    $('#project_manager').val('');
    $('#bid_amount').val('');
    $('#duration').val('');
    $('#status').val('construction');
    $('#project_content').val('');

    $('#cover_image').val('');
    imageUploadUrl = null; // 重置图片URL

    const imgElement = document.getElementById('image_preview');
    imgElement.src = ''; // 清除图片路径
    imgElement.style.display = 'none'; // 隐藏图片

    isEditMode = false;
    currentProjectId = null;
    $('#saveButton').show();
    $('#updateButton').hide();
}

// 图片上传
function uploadImage() {
    const imageFile = document.getElementById('cover_image').files[0];

    if (imageFile) {
        const formData = new FormData();
        formData.append('file', imageFile);

        $.ajax({
            url: "/api/project_upload_img/",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                imageUploadUrl = response.data[0].url;
                alert("图片上传成功");
            },
            error: function () {
                alert("图片上传失败");
            }
        });
    } else {
        alert("请先选择一张图片");
    }
}

// 提交新项目
function submit_project() {
    let name = $('#project_name').val(),
        manager = $('#project_manager').val(),
        bidAmount = $('#bid_amount').val(),
        duration = $('#duration').val(),
        status = $('#status').val(),
        content = $('#project_content').val();  // 获取textarea的值
    postProjectData(name, manager, bidAmount, duration, status, content, imageUploadUrl);
}

// 上传项目数据
function postProjectData(name, manager, bidAmount, duration, status, content, imageUrl) {
    $.ajax({
        url: "/api/project/",
        type: "POST",
        data: JSON.stringify({
            name: name,
            manager: manager,
            bid_amount: bidAmount,
            duration: duration,
            status: status,
            content: content,
            image_url: imageUrl || '' // 如果没有图片，则传入空字符串
        }),
        contentType: "application/json; charset=utf-8",
        success: function () {
            $('#AddModal').modal('hide');
            table.ajax.reload();
            resetForm();
            alert("项目已成功添加");
        },
        error: function () {
            alert("创建项目时发生错误");
        }
    });
}

// 更新项目
function update_project() {
    let name = $('#project_name').val(),
        manager = $('#project_manager').val(),
        bidAmount = $('#bid_amount').val(),
        duration = $('#duration').val(),
        status = $('#status').val(),
        content = $('#project_content').val();  // 获取textarea的值

    // 如果有新上传的图片URL，则使用它；否则使用原始图片URL；两者都不存在则留空
    const imageUrl = imageUploadUrl || originalImageUrl || '';

    putProjectData(name, manager, bidAmount, duration, status, content, imageUrl);
}

// 更新项目数据
function putProjectData(name, manager, bidAmount, duration, status, content, imageUrl) {
    $.ajax({
        url: "/api/project/" + currentProjectId + "/",
        type: "PUT",
        data: JSON.stringify({
            name: name,
            manager: manager,
            bid_amount: bidAmount,
            duration: duration,
            status: status,
            content: content,
            image_url: imageUrl || '' // 如果没有图片，则传入空字符串
        }),
        contentType: "application/json; charset=utf-8",
        success: function () {
            $('#AddModal').modal('hide');
            table.ajax.reload();
            resetForm();
            alert("项目已成功更新");
        },
        error: function () {
            alert("更新项目时发生错误");
        }
    });
}

// 删除项目
function delete_project(projectId) {
    if (confirm("确认是否删除该项目")) {
        $.ajax({
            url: "/api/project/" + projectId + "/",
            type: "DELETE",
            success: function () {
                table.ajax.reload();
                alert("项目已删除");
            },
            error: function () {
                alert("删除失败");
            }
        });
    }
}

// 编辑项目
function edit_project(projectId) {
    $.get("/api/project/" + projectId + "/", function (data) {
        console.log('data数据', data);

        isEditMode = true;
        currentProjectId = projectId;

        $('#saveButton').hide();
        $('#updateButton').show();

        $('#project_name').val(data.name);
        $('#project_manager').val(data.manager);
        $('#bid_amount').val(data.bid_amount);
        $('#duration').val(data.duration);
        $('#status').val(data.status);
        $('#project_content').val(data.content);  // 设置textarea的值

        const imgElement = document.getElementById('image_preview');

        // 检查image_url是否存在，如果不存在则隐藏图像元素
        if (data.image_url) {
            originalImageUrl = data.image_url;
            imgElement.src = data.image_url;
            imgElement.style.display = 'block'; // 显示图片
        } else {
            originalImageUrl = null;
            imgElement.src = '';
            imgElement.style.display = 'none'; // 隐藏图片
        }

        $('#AddModal').modal('show');
    });
}


// 图片预览并添加点击事件来缩放图片
function previewImage() {
    const file = document.getElementById('cover_image').files[0];
    const reader = new FileReader();

    reader.onloadend = function () {
        const imgElement = document.getElementById('image_preview');
        imgElement.src = reader.result;
        imgElement.style.display = 'block';
    };

    if (file) {
        reader.readAsDataURL(file);
        uploadImage(); // 上传图片
    } else {
        const imgElement = document.getElementById('image_preview');
        imgElement.src = '';
        imgElement.style.display = 'none';
    }
}

// 点击图片缩放
$('#image_preview').on('click', function () {
    $(this).toggleClass('enlarged');
});
$(document).ready(function () {
    table = $('#ProjectTable').DataTable({
        "fnPreDrawCallback": function (oSettings) {
            var processing_div = $('#ProjectTable_processing');
            processing_div.removeClass("card");
            processing_div.addClass("align-middle");
        },
        "ajax": {
            url: "/api/project/",
            type: "GET",
            dataSrc: "results"
        },
        "ordering": false,
        "serverSide": false,
        "paging": true,
        "lengthChange": false,
        "searching": true,
        "bProcessing": true,
        "dom": "<'row'<'col-sm-12 col-md-12'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        "language": {
            "sSearch": "",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "没有数据！",
            "sEmptyTable": "当前未查询到信息",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmpty": "显示0到0条记录",
            "sInfoFiltered": "数据表中共有 _MAX_ 条记录",
            "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                '<span class="sr-only">Loading...</span>',
            "sLoadingRecords": '',
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        "columns": [
            { "data": 'name' },
            { "data": 'manager' },
            { "data": 'bid_amount', "render": function (data, type, row) {
                return data + " 万元";
            }},
            { "data": 'duration' },
            { "data": 'status', "render": function (data) {
                const statusMap = {
                    'construction': '施工中',
                    'accepted': '已验收',
                    'not_accepted': '未验收',
                    'overdue_accepted': '工期已过已验收',
                    'abandoned': '放弃中标'
                };
                return statusMap[data] || data;
            }},
            { "data": 'content', "render": function (data, type, row) {
                return '<div class="text-ellipsis-multiline">' + data + '</div>';
            }},
            { "data": {}, "render": function (data) {
                return '<a href="javascript:void(0);" style="text-decoration: none" onclick="edit_project(\'' + data['id'] + '\')">编辑</a>&nbsp;' +
                    '<a href="javascript:void(0);" style="text-decoration: none" onclick="delete_project(\'' + data['id'] + '\')">删除</a>';
            }}
        ]
    });

    $('.dataTables_filter').attr("hidden", "hidden");

    $('#add_project').click(function () {
        resetForm();
    });

    $('#collapseProjects').collapse('show');
    $('a[href="/console/project"]').addClass('active');
});
</script>
{% endblock %}
